import store from '@/store'
import { Toast } from 'antd-mobile'
import axios from 'axios'
import history from './history'
import { getTokenInfo, removeTokenInfo, setTokenInfo } from './storage'

// 请求基地址
export const baseURL = 'http://geek.itheima.net'

// 创建 axios 实例
const http = axios.create({
  baseURL: baseURL,
  timeout: 5000,
})

// 请求拦截器
http.interceptors.request.use(
  function (config: any) {
    // 获取缓存中的 Token 信息
    const { token } = getTokenInfo()
    // 如果有 token
    if (token) {
      // 设置请求头的 Authorization 字段
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    return response.data
  },
  async function (error) {
    if (!error.response) {
      Toast.show({ content: '网络开小差' })
    } else if (error.response.status !== 401) {
      Toast.show({ content: error.response.data.message })
    } else {
      const { refresh_token } = getTokenInfo()
      if (refresh_token) {
        try {
          const res = await axios({
            url: `${baseURL}/v1_0/authorizations`,
            method: 'PUT',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              Authorization: `Bearer ${refresh_token}`,
            },
          })
          const token = res.data.data.token
          const auth = { token, refresh_token }
          setTokenInfo(auth)
          store.dispatch({ type: 'user/saveAuth', payload: auth })
          return http(error.config)
        } catch (error) {
          Toast.show({ content: '登录过期' })
          removeTokenInfo()
          store.dispatch({ type: 'user/clearAuth' })
          history.push('/login', { from: history.location.pathname })
        }
      }
    }
    return Promise.reject(error)
  }
)

// 导出 axios 实例
export default http
